<?php


namespace app\wechat\controller;


use app\common\controller\WechatUserBase;
use app\common\model\GoodsFormat;
use app\common\model\OrderGoods;
use app\common\model\OrderTicketLog;
use app\common\model\ShopMoneyLog;
use app\common\model\UserMoneyLog;
use EasyWeChat\Factory;
use Endroid\QrCode\ErrorCorrectionLevel;
use Endroid\QrCode\QrCode;
use think\Db;
use think\facade\Request;

class Order extends WechatUserBase
{
//    创建订单页面
    public function create(){

        $param = input();
        $this->assign('param',$param);
        $sku = '';
        if (!empty($param['s1'])){
            $sku .= Db::name('goods_format_value')->where('id','=',$param['s1'])->value('name');
        }
        if (!empty($param['s2'])){
            $sku .= ','.Db::name('goods_format_value')->where('id','=',$param['s2'])->value('name');
        }
        if (!empty($param['s3'])){
            $sku .= ','.Db::name('goods_format_value')->where('id','=',$param['s3'])->value('name');
        }
        $this->assign('sku',$sku);

        return view();
    }
//    创建订单
    public function createOrder(){
        $param = input();
        $param['user_id'] = session('wechat.id');
        $goodsModel = new \app\common\model\Goods();
        $orderModel = new \app\common\model\Order();
        $orderGoodsModel = new OrderGoods();
        Db::startTrans();
        try {
            $goods = $goodsModel::where('id',$param['goods_id'])->find();
            if (empty($goods)){
                abort(1,'当前商品不存在或已下架');
            }
//            判断是否限购
            if ($goods['limit_buy_total'] > 0){
//                获取当前用户已经购买了多少商品
                $buy_num = \app\common\model\Order::getUserBuy($param['user_id']);
                if ($buy_num > $goods['limit_buy_total']){
                    abort(1,'当前商品限购'.$goods['limit_buy_total'].'件，您已购买'.$buy_num.'件');
                }
            }
//            查询商品对应规格信息
            $format = GoodsFormat::where('id',$param['sku_id'])->find();
            if ($format['stock'] < $param['num']){
                abort(1,'商品剩余库存不足');
            }

            $param['goods_name'] = $goods['name'];
            $param['share_money_min'] = $goods['share_money_min'];
            $param['share_money_max'] = $goods['share_money_max'];
            $param['share_money'] = rand($param['share_money_min']*100,$param['share_money_max']*100)/100;
            $param['shop_id'] = $goods['shop_id'];

            $param['buyer_name'] = $param['name'];
            if ($param['express'] == 1){
                $param['buyer_tel'] = $param['tel'];
                $param['buyer_postalCode'] = $param['postalCode'];
                $param['buyer_province'] = $param['province'];
                $param['buyer_city'] = $param['city'];
                $param['buyer_county'] = $param['county'];
                $param['buyer_address'] = $param['addressDetail'];
            }
            $param['buy_mode'] = 'BUY';

            $param['ticket_code'] = \app\common\model\Order::getTicketCode($param['buy_mode']);
            $param['order_sn'] = \app\common\model\Order::getOrderSn();

            $orderModel->allowField(true)->save($param);
            $order_id = $orderModel->id;

            $goods = $goods->toArray();
            $goods['goods_id'] = $goods['id'];
            $goods['order_id'] = $order_id;
            unset($goods['id']);
            $orderGoodsModel->allowField(true)->isUpdate(false)->save($goods);
            Db::commit();
            //            生成支付jssdk
            $getJssdk = json_decode(self::getOrderPayJssdk($order_id),true);
            if ($getJssdk['code'] == 1){
                abort(1,$getJssdk['msg']);
            }else{
                $json = $getJssdk['data'];
            }
        }catch (\Exception $e){
            Db::rollback();
            $this->error($e->getMessage());
        }

        $this->success('创建订单成功，请支付','',['order_id'=>$order_id,'jssdk'=>$json]);
    }
//    创建店铺买单
    public function createOrderShop(){
        $param = input();

        Db::startTrans();
        try {
            $shop = \app\common\model\Shop::where('id','=',$param['shop_id'])->find();
            if (empty($shop)){
                abort(1,'当前店铺不存在或已停业，请重新进入');
            }

            $param['user_id'] = session('wechat.id');
            $param['buy_mode'] = 'SHOPBUY';
            $param['goods_name'] = $shop['name'].'店铺买单';
            $param['total_price'] = $param['price'];
            $param['num'] = 1;
            $param['order_sn'] = \app\common\model\Order::getOrderSn();


            $orderModel = new \app\common\model\Order();
            $orderModel->allowField(true)->save($param);
            $order_id = $orderModel->id;
            Db::commit();

            //            生成支付jssdk
            $getJssdk = json_decode(self::getOrderPayJssdk($order_id),true);
            if ($getJssdk['code'] == 1){
                abort(1,$getJssdk['msg']);
            }else{
                $json = $getJssdk['data'];
            }
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success('提交订单成功','',['order_id'=>$order_id,'json'=>$json]);
    }
    //    获取订单列表
    public function getOrderList(){
        $param = input();
        $where = [];
        $total = 0;

        if (isset($param['user_id']) && is_numeric($param['user_id']) && $param['user_id'] > 0){
            $where[] = ['user_id','=',$param['user_id']];
        }

        if (isset($param['share_id']) && is_numeric($param['share_id']) && $param['share_id'] > 0){
            $where[] = ['share_id','=',$param['share_id']];
            $total = Db::name('order')->where('share_id','=',$param['share_id'])->sum('share_money');
        }


        if (is_numeric($param['order_status']) && $param['order_status'] > 0){
            $where[] = ['order_status','=',$param['order_status']];
        }

        if (isset($param['shop_id']) && is_numeric($param['shop_id']) && $param['shop_id'] > 0){
            $where[] = ['shop_id','=',$param['shop_id']];
        }

        if (!empty($param['buy_mode'])){
            $where[] = ['buy_mode','=',$param['buy_mode']];
        }

        $data = \app\common\model\Order::with(['goods','shop','user'])->where($where)->order('id desc')->paginate($param['limit'],false,['query'=>$param]);
        foreach ($data as $k=>&$v){
            if (isset($v['img_thumb'])){
                $v['img_thumb'] = getFullPath($v['img_thumb']);
            }

            if($v['buy_mode'] == 'SHOPBUY'){
                $v['img_thumb'] = getFullPath($v['shop_img_thumb']);
            }

            $v['pay_status_text'] = $v->pay_status_text;
            $v['order_status_text'] = $v->order_status_text;
            $v['buy_mode_text'] = $v->buy_mode_text;
            $v['total_price'] = number_format($v['total_price'],2)/100*100;
        }

        return $this->result($data,$total);
    }

    //    取消订单
    public function cancelOrder(){
        $order_id = input('order_id');
        $order = new \app\common\model\Order();
        $res = $order->isUpdate(true)->save(['order_status'=>20],['id'=>$order_id]);
        if ($res !== false){
            $this->success();
        }else{
            $this->error();
        }
    }

    //    获取订单详情
    public function getOrderDetail(){
        $order_id = input('order_id');
        $ticket_code = input('ticket_code');
        if (empty($order_id) && !empty($ticket_code)){
            $order_id = Db::name('order')->where('ticket_code','=',$ticket_code)->value('id');
            if (empty($order_id)){
                return $this->error('核验码不存在，请检查后重新输入');
            }
        }

        if (empty($order_id)){
            return $this->error('信息错误，请重新扫码进入');
        }

        $param = input();


        require_once app()->getRootPath().'/extend/phpqrcode/phpqrcode.php';
        $txt = url('callBack/checkTicket',['order_id'=>$order_id],'',true);
        $picPathAndName = app()->getRootPath()."/public/qrcode/order/".$order_id.'.png';//二维码保存路径和名称
        $level = 'H';$size = 5;$is_logo = 1;//是否包含Logo 0否 1是
        $margin = 2;//边距
        $saveAndPrint = true;//是否保存，保存时，$picPathAndName设置为true//生成二维码图片
        \QRcode::png($txt, $picPathAndName, $level, $size, $margin,$saveAndPrint);if($is_logo == 1){
            $QR = $picPathAndName; //已经生成的原始二维码图
            $Logo = app()->getRootPath().'/public/static/wechat/img/qrcode_logo.jpg';
            $Logo_re =$picPathAndName;

            $QR = imagecreatefromstring(file_get_contents($QR));
            $Logo = imagecreatefromstring(file_get_contents($Logo));
            $QR_width = imagesx($QR); //二维码图片宽度
            $QR_height = imagesy($QR); //二维码图片高度
            $logo_width = imagesx($Logo); //logo图片宽度
            $logo_height = imagesy($Logo); //logo图片高度
            $logo_qr_width = $QR_width / 5;
            $scale = $logo_width / $logo_qr_width;
            $logo_qr_height = $logo_height / $scale;
            $from_width = ($QR_width - $logo_qr_width) / 2;
            imagecopyresampled($QR, $Logo, $from_width, $from_width, 0, 0, $logo_qr_width, $logo_qr_height, $logo_width, $logo_height);
            //输出图片
            imagepng($QR, $Logo_re);
        }

        $data = \app\common\model\Order::where('id','=',$order_id)->find();

        //        付款
        $json = [];
        if (isset($param['patType']) && $param['patType']){
            $getJssdk = json_decode($this->getOrderPayJssdk($order_id),true);
            if ($getJssdk['code'] == 1){
                $this->error($getJssdk['msg']);
            }else{
                $json = $getJssdk['data'];
            }
            $data = \app\common\model\Order::where('id','=',$order_id)->find();
        }

        $data['ticket_qrcode'] = getFullPath("/qrcode/order/".$order_id.'.png');

        $data['shop'] = \app\common\model\Shop::where('id','=',$data['shop_id'])->find();

        $data['goods'] = \app\common\model\Goods::where('id','=',$data['goods_id'])->find();
        if (!empty($data['goods']) && isset($data['goods']['img_thumb'])){
            $data['goods']['img_thumb'] = getFullPath($data['goods']['img_thumb']);
        }

        $data['pay_status_text'] = $data->pay_status_text;
        $data['order_status_text'] = $data->order_status_text;
        $data['buy_mode_text'] = $data->buy_mode_text;


        $data['json'] = $json;
        $this->result($data);
    }

//    获取支付的jssdk
    public function getOrderPayJssdk($order_id){
        $order = \app\common\model\Order::with(['user'])->where('id',$order_id)->find();
        $diff_time = time() - strtotime($order['create_time']);
        if ($diff_time > 300){
            \app\common\model\Order::where('id',$order_id)->update(['order_status'=>20]);
            return json_encode(['code'=>1,'msg'=>'订单已过期请重新下单']);
        }
        //            生成支付jssdk
        $wechatConfig = config('wechat.');
        $wechatConfig['notify_url'] = url('CallBack/payCallBack',['order_id'=>$order_id],'',true);
        $app = Factory::payment($wechatConfig);
        //            重新生成订单号
        $order_sn = \app\common\model\Order::getOrderSn();
        $result = $app->order->unify([
            'body' => mb_substr($order['goods_name'], 0, 30, 'utf-8'),
            'out_trade_no' => $order_sn,
            'total_fee' => $order['total_price']*100,
            'trade_type' => 'JSAPI', // 请对应换成你的支付方式对应的值类型
            'openid' => $order['openid'],
        ]);
        $prepayId = null;
        if ($result['return_code'] == 'SUCCESS' && $result['result_code'] == 'SUCCESS') {
//            更新订单编号
            Db::name('order')->where('id',$order_id)->update(['order_sn'=>$order_sn]);
            $prepayId = $result['prepay_id'];
            $jssdk = $app->jssdk;
            $json = $jssdk->sdkConfig($prepayId);
            return json_encode(['code'=>0,'data'=>$json]);
        } else {
            return json_encode(['code'=>1,'msg'=>$result]);
        }
    }

    //    核销
    public function checkOrderTicketCode(){
        $ticket_code = input('ticket_code');
        $order_id = input('order_id');

        if (empty($order_id) && !empty($ticket_code)){
            $order_id = Db::name('order')->where('ticket_code','=',$ticket_code)->value('id');
            if (empty($order_id)){
                $this->error('核验码不存在，请检查后重新输入');
            }
        }

        if (empty($order_id)){
            $this->error('信息错误，请从新扫码进入');
        }

        $order = Db::name('order')->where('id','=',$order_id)->find();
        if (!empty($order) && $order['ticket_code'] == $ticket_code){

            if ($order['order_status'] != 30){
                $this->error('当前订单已被核验');
            }else{
                // 启动事务
                Db::startTrans();
                try {
//                    更改订单状态
                    $orderModel = new \app\common\model\Order();
                    $orderModel->isUpdate(true)->save(['order_status'=>50],['id'=>$order_id]);
//                    写入核销记录
                    $orderTicketLog = new OrderTicketLog();
                    $orderTicketLog->isUpdate(false)->save(['order_id'=>$order_id,'ticket_code'=>$ticket_code,'user_id'=>session('wechat.id')]);
//                    如果有返利金额
                    $share_money = $order['share_money'];
                    $total_price = $order['total_price'];
                    if ($share_money > 0){
//                            如果返利金额比销售金额小，那么返利金额，就等于销售金额
                        if ($share_money <= $total_price){
                            $share_money = $total_price;
                        }

                        Db::name('user')->where('id',$order['share_id'])->setInc('money',$share_money);
                        UserMoneyLog::saveLog($order['share_id'],'inc',$share_money,$order['id'],$order['order_sn'],'订单返利增加');
                    }
                    Db::name('shop')->where('id',$order['shop_id'])->setInc('money',$total_price - $share_money);
                    ShopMoneyLog::saveLog($order['shop_id'],'inc',$total_price - $share_money,$order['id'],$order['order_sn'],'订单核销增加');
                    // 提交事务
                    Db::commit();
                } catch (\Exception $e) {
                    // 回滚事务
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                $this->success('核验成功');
            }

        }else{
            $this->error('核验码错误');
        }

    }
}
